﻿using MapleLeaf.Pay;
using Microsoft.Win32;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace MapleLeaf.Client{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application {

        public static readonly Process CurrentProcess = Process.GetCurrentProcess();

        public static readonly Assembly Assembly = Assembly.GetEntryAssembly();

        public static FileInfo FileInfo = new FileInfo(CurrentProcess.MainModule.FileName);

        public static Timer AutoStartTimer;


        public static string Version { get; } = Assembly.GetName().Version.ToString();

        public static string Title { get; } = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly, typeof(AssemblyTitleAttribute))).Title;

        public static string ProductName { get; } = ((AssemblyProductAttribute)Attribute.GetCustomAttribute(Assembly, typeof(AssemblyProductAttribute))).Product;

        public static string CopyRight { get; } = ((AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(Assembly, typeof(AssemblyCopyrightAttribute))).Copyright;

        public static string Descript { get; } = ((AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(Assembly, typeof(AssemblyDescriptionAttribute))).Description;


        public static Dictionary<string, string> Args { get; } = new Dictionary<string, string>();


        private App() {
            ThreadPool.SetMinThreads(50, 50);
            Environment.CurrentDirectory = Path.GetDirectoryName(FileInfo.FullName);
            DispatcherUnhandledException += App_DispatcherUnhandledException;
        }


        protected override void OnStartup(StartupEventArgs e) {
            foreach (string text in e.Args) {
                string[] array = text.Split(new char[]
                {
                    '='
                }, 2);
                Args.Add(array[0], (array.Length > 1) ? array[1] : null);
            }
            CloseCurrentProcess();
            if (FileInfo.Name.EndsWith(Patcher.PatchSuffix, StringComparison.OrdinalIgnoreCase)) {
                string text2 = FileInfo.FullName.Substring(0, FileInfo.FullName.Length - Patcher.PatchSuffix.Length);
                for (int j = 0; j < 10; j++) {
                    try {
                        File.SetAttributes(text2, FileAttributes.Normal);
                        File.Copy(FileInfo.FullName, text2, true);
                        break;
                    }
                    catch {
                        Thread.Sleep(500);
                    }
                }
                Process.Start(text2);
                Environment.Exit(0);
            }
            else {
                if (!Directory.Exists("native")) {
                    Patcher ProductPatcher = new Patcher();
                    PatchContext ProductPatchContext = new PatchContext(ProductName);
                    if (ProductPatcher.CheckPatch(ProductPatchContext)) {
                        new PatchWindow(ProductPatchContext).Show();
                        Task task = new Task(delegate () {
                            if (ProductPatcher.Download(ProductPatchContext)) {
                                Patcher.Patch(ProductPatchContext);
                            }
                        });
                        task.Start();
                        return;
                    }
                }
                AddAutoStartup();
                AutoStartTimer = new Timer(new TimerCallback(AutoStartTimerCallBack), null, 30000, 30000);
                Current.StartupUri = new Uri("pack://application:,,,/MainWindow.xaml");
                base.OnStartup(e);
            }
        }


        private void AutoStartTimerCallBack(object state) {
            DateTime now = DateTime.Now;
            if (CurrentProcess.StartTime.Date != now.Date && now.Hour == 4) {
                Process.Start(FileInfo.FullName);
            }
        }

 
        public static void ProcessException(Exception e) {
            MessageBox.Show(e.GetMessage(), FileInfo.Name, MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK, MessageBoxOptions.ServiceNotification);
        }

     
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) {
            e.Handled = true;
            ProcessException(e.Exception);
        }

       
        private static void AddAutoStartup() {
            RegistryKey registryKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
            try {
                registryKey.SetValue(ProductName, FileInfo.FullName);
            }
            catch (Exception) {
            }
            Registry.CurrentUser.Close();
        }

        private static void CloseCurrentProcess() {
            Process[] processes = Process.GetProcesses();
            foreach (Process process in processes) {
                try {
                    if (process.MainModule.FileVersionInfo.ProductName == ProductName && process.Id != CurrentProcess.Id) {
                        process.Kill();
                        process.WaitForExit();
                    }
                }
                catch {
                }
            }
        }

        

    }
}